"""
Case Type   : 系统内部使用工具
Case Name   : 运行事务不提交，gs_ctl restart不指定-w启动数据库，事务是否回滚
Create At   : 2021/01/25
Owner       : opentestcase015
Description :
    1.开启并执行事务(不做提交)
    2.开启新的session使用gs_ctl restart进行重启（不指定-w）
    3.查看主机状态与事务是否回滚
    4.恢复集群状态
Expect      :
    1.开启且执行事务成功
    2.开启新的session使用gs_ctl restart进行重启成功，未等待事务
    3.主机状态正常、事务回滚
    4.成功
History     :
    Modified by lopentestcase027 2023/1/10: 优化用例步骤格式及一主两备判断方式
"""

import unittest
import time
import os
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro

LOG = Logger()
primary_sh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != primary_sh.get_node_num(), '非1+2环境不执行')
class SystemInternalTools(unittest.TestCase):
    def setUp(self):
        LOG.info(f'--------{os.path.basename(__file__)} start--------')
        self.constant = Constant()
        self.PrimaryNode = Node('PrimaryDbUser')
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.StandbyNode = Node('Standby1DbUser')
        self.sh_standby = CommonSH('Standby1DbUser')
        self.t_name = 't_gs_ctl_0024'

    def test_system_internal_tools(self):
        LOG.info('--------step1:开启并执行事务  expect:开启且执行事务成功--------')
        transaction_msg = self.sh_primary.execut_db_sql(f'''drop table if
            exists {self.t_name}; 
            start transaction; 
            create table {self.t_name} (a integer);''')
        LOG.info(transaction_msg)
        self.assertIn(self.constant.TABLE_CREATE_SUCCESS, transaction_msg)
        self.assertIn(self.constant.START_TRANSACTION_SUCCESS_MSG,
                      transaction_msg)

        LOG.info('--------step2:使用gs_ctl重启主机  expect:重启成功--------')
        self.restart_cmd = f'''source {macro.DB_ENV_PATH};
            gs_ctl restart -D {macro.DB_INSTANCE_PATH} -M primary ;
            '''
        LOG.info(self.restart_cmd)
        restart_msg = self.PrimaryNode.sh(self.restart_cmd).result()
        LOG.info(restart_msg)
        self.assertIn(self.constant.RESTART_SUCCESS_MSG, restart_msg)
        time.sleep(10)

        LOG.info('--------step3:校验主机状态并查询事务 '
                 'expect:主机状态正常、事务回滚--------')
        status = self.sh_primary.get_db_instance_status()
        self.assertTrue(status)
        transaction_msg = self.sh_primary.execut_db_sql(
            f'select count(*) from {self.t_name}')
        LOG.info(transaction_msg)
        self.assertIn(self.constant.NOT_EXIST, transaction_msg)

    def tearDown(self):
        LOG.info('--------step4:恢复集群状态 expect:成功--------')
        recover = self.sh_primary.restart_db_cluster()
        LOG.info(recover)
        self.assertTrue(recover)
        recover_msg = self.sh_standby.get_db_cluster_status(param='detail')
        LOG.info(recover_msg)
        self.assertTrue(self.constant.CLUSTER_NORMAL_MSG in recover_msg)
        LOG.info(f'--------{os.path.basename(__file__)} end--------')
